import api from './api';
import { FileInfo, UploadChunkParams, ChunksParams } from '../types/file';

/**
 * 分片上传功能
 * @param params 分片上传参数
 * @returns 上传结果
 */
export async function uploadChunk(params: UploadChunkParams): Promise<FileInfo> {
  try {
    const formData = new FormData();
    formData.append('chunkFile', params.chunkFile);
    formData.append('chunkIndex', params.chunkIndex.toString());
    formData.append('totalChunks', params.totalChunks.toString());
    formData.append('fileName', params.fileName);
    formData.append('uploadId', params.uploadId);

    const response = await api.post('/api/file/uploadChunk', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data;
  } catch (error) {
    console.error('分片上传失败:', error);
    throw new Error('分片上传失败，请检查网络连接或稍后重试');
  }
}

/**
 * 合并分片功能
 * @param params 合并分片参数
 * @returns 合并结果
 */
export async function mergeChunks(params: ChunksParams): Promise<FileInfo> {
  try {
    const response = await api.post('/api/file/mergeChunks', params);
    return response.data;
  } catch (error) {
    console.error('分片合并失败:', error);
    throw new Error('分片合并失败，请检查网络连接或稍后重试');
  }
}

/**
 * 查询已上传的分片
 * @param params 查询参数
 * @returns 已上传分片信息
 */
export async function getUploadedChunks(params: ChunksParams): Promise<number[]> {
  try {
    const response = await api.get('/api/file/uploadedChunks', {
      params: {
        uploadId: params.uploadId,
        fileName: params.fileName,
      },
    });
    return response.data;
  } catch (error) {
    console.error('查询已上传分片失败:', error);
    throw new Error('查询已上传分片失败，请检查网络连接或稍后重试');
  }
}

/**
 * 普通文件上传功能
 * @param file 要上传的文件
 * @returns 上传结果
 */
export async function uploadFile(file: File): Promise<FileInfo> {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await api.post('/api/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data;
  } catch (error) {
    console.error('文件上传失败:', error);
    throw new Error('文件上传失败，请检查网络连接或稍后重试');
  }
}

/**
 * 获取文件信息
 * @param fileId 文件ID
 * @returns 文件详细信息
 */
export async function getFileInfo(fileId: string): Promise<FileInfo> {
  try {
    const response = await api.get(`/api/file/${fileId}`);
    return response.data;
  } catch (error) {
    console.error('获取文件信息失败:', error);
    throw new Error('获取文件信息失败，请检查网络连接或稍后重试');
  }
}

/**
 * 文件下载功能
 * @param fileId 文件ID
 * @returns 文件下载流
 */
export async function downloadFile(fileId: string): Promise<void> {
  try {
    const response = await api.get(`/api/file/download/${fileId}`, {
      responseType: 'blob',
    });

    // 创建下载链接并触发下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    
    // 尝试从响应头中获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'downloaded-file';
    if (contentDisposition) {
      const match = /filename="?([^;"]+)"?/.exec(contentDisposition);
      if (match && match[1]) {
        fileName = match[1];
      }
    }
    
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('文件下载失败:', error);
    throw new Error('文件下载失败，请检查网络连接或稍后重试');
  }
}